<template>
  <div class="login-container">
    <!-- 头部 -->
    <div class="header d-flex align-items-center">
      <h5 class="mb-0 mx-auto">登录</h5>
    </div>
    <form @submit.prevent="handleLogin" class="login-form" aria-label="登录表单">
      <!-- 登录表单 -->
      <div class="login-form">
        <!-- 原有用户名密码登录部分 -->
        <div v-if="loginType === 'account'">
          <div class="form-group mb-3">
            <div class="input-group">
              <span class="input-group-text">
                <i class="bi bi-person"></i>
              </span>
              <input
                  type="text"
                  class="form-control"
                  v-model="loginForm.username"
                  placeholder="请输入用户名或手机号"
                  id="username"
                  required
                  autocomplete="username"
                  aria-required="true"
              >
            </div>
          </div>

          <div class="form-group mb-4">
            <div class="input-group">
              <span class="input-group-text">
                <i class="bi bi-lock"></i>
              </span>
              <input
                  type="password"
                  class="form-control"
                  id="password"
                  v-model="loginForm.password"
                  placeholder="请输入密码"
                  required
              >
            </div>
          </div>
        </div>

        <!-- 手机号验证码登录部分 -->
        <div v-if="loginType === 'phone'">
          <div class="form-group mb-3">
            <div class="input-group">
              <span class="input-group-text">
                <i class="bi bi-telephone"></i>
              </span>
              <input
                  type="text"
                  class="form-control"
                  v-model="loginForm.phone"
                  placeholder="请输入手机号"
                  id="phone"
                  required
              >
            </div>
          </div>

          <div class="form-group mb-4">
            <div class="input-group">
              <span class="input-group-text">
                <i class="bi bi-lock"></i>
              </span>
              <input
                  type="text"
                  class="form-control"
                  id="verificationCode"
                  v-model="loginForm.verificationCode"
                  placeholder="请输入验证码"
                  required
              >
              <button class="btn btn-outline-secondary" type="button" @click="sendVerificationCode" :disabled="countdown > 0">
                {{ countdown > 0 ? `${countdown} 秒后重试` : '获取验证码' }}
              </button>
            </div>
          </div>
        </div>

        <button
            class="btn btn-primary w-100 mb-3"
        >
          登录
        </button>
        <div class="text-center mb-4">
          <!-- 切换登录方式 -->
          <button class="btn btn-link" @click="toggleLoginType">{{ loginType === 'account' ? '使用手机号登录' : '使用账号密码登录' }}</button>
          <!-- 错误信息显示 -->
          <div v-if="errorMessage" class="alert alert-danger mb-3">
            {{ errorMessage }}
          </div>
        </div>

        <div class="text-center">
          <router-link to="/register" class="text-decoration-none">
            还没有账号？立即注册
          </router-link>
          <br><br>
          <router-link to="/forgot-password" class="text-decoration-none">
            忘记密码？找回密码
          </router-link>
        </div>
      </div>
    </form>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import http from '../../router/http'
import router from "@/router/index";

// 登录表单数据
const loginForm = ref({ username: '', password: '', phone: '', verificationCode: '' ,loginType: 'account'})
// 错误信息
const errorMessage = ref('')
// 登录类型，account 表示账号密码登录，phone 表示手机号验证码登录
const loginType = ref('account')
// 倒计时
const countdown = ref(0)

// 处理登录逻辑
const handleLogin = async () => {
  errorMessage.value = '' // 重置错误信息

  if (loginType.value === 'account') {
    // 账号密码登录验证
    if (!loginForm.value.username || !loginForm.value.password) {
      errorMessage.value = '请输入用户名和密码'
      return
    }
    loginForm.value.loginType = 'account'
    try {
      const response = await http.post('/user/login', loginForm.value);
      const data = await response.data
      if (response.status === 200 && data.code === 1) {
        localStorage.setItem('token', data.response.token)
        localStorage.setItem('userId', data.response.userId);
        localStorage.setItem('role', data.response.role)
        if (data.response.role === 1) {
          router.push('/english')
        } else if (data.response.role === 3) {
          router.push('/groups')
        }
      } else {
        errorMessage.value = data.message || '用户名或密码错误'
      }
    } catch (error) {
      console.error(error)
      errorMessage.value = '网络错误，请稍后重试'
    }
  } else if (loginType.value === 'phone') {
    // 手机号验证码登录验证
    if (!loginForm.value.phone || !loginForm.value.verificationCode) {
      errorMessage.value = '请输入手机号和验证码'
      return
    }

    try {
      const response = await http.post('/student/user/loginByPhoneCode?phone='+loginForm.value.phone
          +'&validCode='+loginForm.value.verificationCode,);
      const data = await response.data
      if (response.status === 200 && data.code === 1) {
        localStorage.setItem('token', data.response.token)
        localStorage.setItem('userId', data.response.userId);
        localStorage.setItem('role', data.response.role)
        if (data.response.role === 1) {
          router.push('/english')
        } else if (data.response.role === 3) {
          router.push('/groups')
        }
      } else {
        errorMessage.value = data.message || '手机号或验证码错误'
      }
    } catch (error) {
      console.error(error)
      errorMessage.value = '网络错误，请稍后重试'
    }
  }
}

// 发送验证码
const sendVerificationCode = async () => {
  if (!loginForm.value.phone) {
    errorMessage.value = '请输入手机号'
    return
  }

  if (countdown.value > 0) {
    return
  }

  try {
    const response = await http.post('/student/user/sendSmsCode', { phone: loginForm.value.phone,sendType: 3 });
    const data = await response.data
    if (response.status === 200 && data.code === 1) {
      // 验证码发送成功，可以添加一些提示信息
      console.log('验证码发送成功')
      countdown.value = 60
      const timer = setInterval(() => {
        if (countdown.value > 0) {
          countdown.value--
        } else {
          clearInterval(timer)
        }
      }, 1000)
    } else {
      errorMessage.value = data.message || '验证码发送失败'
    }
  } catch (error) {
    console.error(error)
    errorMessage.value = '网络错误，请稍后重试'
  }
}

// 切换登录方式
const toggleLoginType = () => {
  loginType.value = loginType.value === 'account' ? 'phone' : 'account'
  // 重置表单数据
  loginForm.value = { username: '', password: '', phone: '', verificationCode: '' }
  errorMessage.value = ''
}
</script>

<style scoped>
.login-container {
  background-color: #f0f9f9;
  min-height: 100vh;
}

.header {
  padding: 15px;
  background: white;
  position: sticky;
  top: 0;
  z-index: 1000;
  box-shadow: 0 2px 4px rgba(0,0,0,0.05);
}

.login-form {
  background: white;
  margin: 20px 15px;
  padding: 20px;
  border-radius: 15px;
}

.input-group-text {
  background-color: white;
  border-right: none;
}

.form-control {
  border-left: none;
}

.form-control:focus {
  box-shadow: none;
  border-color: #ced4da;
}

.btn-primary {
  background: #40e0d0;
  border: none;
  padding: 12px;
  border-radius: 8px;
}

.btn-primary:hover {
  background: #3bcdc0;
}

a {
  color: #40e0d0;
}

a:hover {
  color: #3bcdc0;
}

/* 分割线样式 */
.divider {
  text-align: center;
  position: relative;
}

.divider::before,
.divider::after {
  content: '';
  position: absolute;
  top: 50%;
  width: calc(50% - 60px);
  height: 1px;
  background-color: #dee2e6;
}

.divider::before {
  left: 0;
}

.divider::after {
  right: 0;
}

.divider span {
  background: white;
  padding: 0 15px;
  color: #6c757d;
  font-size: 0.9rem;
}

/* 微信登录按钮样式 */
.wechat-btn {
  width: 50px;
  height: 50px;
  padding: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px solid #dee2e6;
}

.wechat-btn:hover {
  background-color: #f8f9fa;
}
</style>